<?php


namespace HikCloud;

use HikCloud\Exception\InvalidAccountException;

use think\facade\Cache;

class AccessToken
{

    protected $config;

    protected $cache;

    protected $prefix;

    protected $token;

    protected $cacheKey;

    public function __construct($config)
    {
        $this->getCacheKey();
        $this->config = $config;
        $this->config['client']['grant_type'] = 'client_credentials';
    }

    public function getToken()
    {
        if (!$access_token = Cache::get($this->cacheKey . '_access_token')) {
            $request = HikRequest::getInstance();
            $request->initRequest('OAuth.Token', $this->config['client']);
            $result = $request->sendRequest();
            if (!isset($result['access_token'])) {
                Cache::deleteItem($this->cacheKey . '_access_token');
                return false;
            } else {
                Cache::set($this->cacheKey . '_access_token', $result);
                return $result;
            }
        }
        return $access_token;
    }

    public function getCacheKey()
    {
        return $this->cacheKey = $this->prefix . $this->config['client']['client_id'];
    }

}